package Demo2;


public class SingleLinkedList {
    private ListNode head;

    class ListNode{
        private int val;
        private ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }

    //头插法
    public void addFirst(int data){
        ListNode node = new ListNode(data);

        node.next = head;
        head = node;
    }

    //尾插法
    public void addLast(int data){
        ListNode cur = head;

        while (cur.next != null){
            cur = cur.next;
        }

        ListNode node = new ListNode(data);
        cur.next = node;
    }

    //任意位置插入,第一个数据节点为0号下标
    public boolean addIndex(int index,int data){
        //判断下标是否合理
        if (index < 0 || index > this.size()){
            return false;
        }

        if(index == 0){
            addFirst(data);
            return true;
        }

        if (index == this.size()){
            addLast(data);
            return true;
        }

        ListNode cur = head;
        for (int i = 0; i < index; i++) {
            cur = cur.next;
        }

        ListNode node = new ListNode(data);
        node.next = cur.next;
        cur.next = node;

        return true;
    }

    //查找是否包含关键字key是否在单链表当中
    public boolean contains(int key){
        ListNode cur = head;
        for (int i = 0; i < this.size() - 1; i++) {
            if (cur.val != key){
                cur = cur.next;
            }else{
                return true;
            }
        }
        return false;
    }

    //删除第一次出现关键字为key的节点
    public void remove(int key){
        ListNode cur = head;

        while (cur.next.val != key){
            cur = cur.next;
        }

        cur.next = cur.next.next;

    }

    //删除所有值为key的节点
    public void removeAllKey(int key){
        ListNode cur = head;
        for (int i = 0; i < this.size() - 1; i++) {
            if (cur.next.val != key){
                cur = cur.next;
            }

            cur.next = cur.next.next;
        }
    }
    //得到单链表的长度
    public int size(){
        ListNode cur = head;

        int count = 0;
        while (cur != null){
            cur = cur.next;
            count++;
        }

        return count;
    }

    public void display(){
        ListNode cur = head;
        for (int i = 0; i < this.size() - 1; i++) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
    }
    public void clear(){
        ListNode cur = head;
        ListNode curNext = cur.next;

        for (int i = 0; i < this.size() - 1; i++) {
            cur.next = null;
            cur = curNext;
            curNext = curNext.next;
        }
    }
}
